<template>
  <div class="product-info">
    <div class="page-header">
      <h1>管廊系统产品信息</h1>
      <div class="header-actions">
        <t-button theme="primary" @click="handleAdd">
          <template #icon><t-icon name="add" /></template>
          添加产品
        </t-button>
        <t-input
          v-model="searchText"
          placeholder="搜索产品"
          style="width: 200px; margin-left: 16px"
          clearable
        >
          <template #suffix-icon>
            <t-icon name="search" @click="onSearch" />
          </template>
        </t-input>
      </div>
    </div>

    <t-table
      :columns="columns"
      :data="filteredProducts"
      :loading="loading"
      :pagination="{ pageSize: 10 }"
      bordered
      row-key="id"
    >
      <template #status="{ row }">
        <t-tag :theme="row.status === '在用' ? 'success' : 'warning'" variant="light">
          {{ row.status }}
        </t-tag>
      </template>
      <template #op="{ row }">
        <t-space>
          <t-link theme="primary" hover="color" @click="handleEdit(row)">编辑</t-link>
          <t-link theme="primary" hover="color" @click="handleView(row)">查看详情</t-link>
          <t-link theme="danger" hover="color" @click="showDeleteConfirm(row)">删除</t-link>
        </t-space>
      </template>
    </t-table>

    <!-- 添加/编辑产品对话框 -->
    <t-dialog
      v-model:visible="modalVisible"
      :header="modalTitle"
      :confirm-loading="confirmLoading"
      @confirm="handleModalOk"
    >
      <t-form
        ref="formRef"
        :data="formState"
        :rules="rules"
        :label-width="100"
      >
        <t-form-item label="产品名称" name="name">
          <t-input v-model="formState.name" />
        </t-form-item>
        <t-form-item label="产品型号" name="model">
          <t-input v-model="formState.model" />
        </t-form-item>
        <t-form-item label="产品类别" name="category">
          <t-select v-model="formState.category">
            <t-option value="监控设备" label="监控设备" />
            <t-option value="传感器" label="传感器" />
            <t-option value="控制设备" label="控制设备" />
            <t-option value="通信设备" label="通信设备" />
            <t-option value="其他" label="其他" />
          </t-select>
        </t-form-item>
        <t-form-item label="制造商" name="manufacturer">
          <t-input v-model="formState.manufacturer" />
        </t-form-item>
        <t-form-item label="生产日期" name="productionDate">
          <t-date-picker v-model="formState.productionDate" style="width: 100%" />
        </t-form-item>
        <t-form-item label="使用状态" name="status">
          <t-select v-model="formState.status">
            <t-option value="在用" label="在用" />
            <t-option value="停用" label="停用" />
            <t-option value="维修" label="维修" />
          </t-select>
        </t-form-item>
        <t-form-item label="产品描述" name="description">
          <t-textarea v-model="formState.description" :rows="4" />
        </t-form-item>
      </t-form>
    </t-dialog>

    <!-- 产品详情对话框 -->
    <t-dialog
      v-model:visible="detailsVisible"
      header="产品详情"
      :footer="false"
      width="700px"
    >
      <div v-if="currentProduct" class="product-details">
        <t-descriptions bordered :column="2">
          <t-descriptions-item label="产品ID" :span="1">{{ currentProduct.id }}</t-descriptions-item>
          <t-descriptions-item label="产品名称" :span="1">{{ currentProduct.name }}</t-descriptions-item>
          <t-descriptions-item label="产品型号" :span="1">{{ currentProduct.model }}</t-descriptions-item>
          <t-descriptions-item label="产品类别" :span="1">{{ currentProduct.category }}</t-descriptions-item>
          <t-descriptions-item label="制造商" :span="1">{{ currentProduct.manufacturer }}</t-descriptions-item>
          <t-descriptions-item label="生产日期" :span="1">{{ currentProduct.productionDate }}</t-descriptions-item>
          <t-descriptions-item label="使用状态" :span="1">
            <t-tag :theme="currentProduct.status === '在用' ? 'success' : 'warning'" variant="light">
              {{ currentProduct.status }}
            </t-tag>
          </t-descriptions-item>
          <t-descriptions-item label="产品描述" :span="2">{{ currentProduct.description }}</t-descriptions-item>
        </t-descriptions>

        <div class="product-image" v-if="currentProduct.image">
          <h3>产品图片</h3>
          <div class="image-container">
            <img :src="currentProduct.image" alt="产品图片" />
          </div>
        </div>

        <div class="product-specs" v-if="currentProduct.specifications">
          <h3>技术规格</h3>
          <t-table
            :columns="specColumns"
            :data="currentProduct.specifications"
            bordered
            row-key="key"
            :pagination="false"
          />
        </div>
      </div>
    </t-dialog>

    <!-- 删除确认对话框 -->
    <t-dialog
      v-model:visible="deleteConfirmVisible"
      header="确认删除"
      body="确定要删除这个产品吗?"
      @confirm="confirmDelete"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import dayjs from 'dayjs';

// 表格列定义
const columns = [
  {
    colKey: 'id',
    title: '产品ID',
    width: '80',
  },
  {
    colKey: 'name',
    title: '产品名称',
    width: '150',
  },
  {
    colKey: 'model',
    title: '产品型号',
    width: '120',
  },
  {
    colKey: 'category',
    title: '产品类别',
    width: '120',
  },
  {
    colKey: 'manufacturer',
    title: '制造商',
    width: '150',
  },
  {
    colKey: 'productionDate',
    title: '生产日期',
    width: '120',
  },
  {
    colKey: 'status',
    title: '使用状态',
    width: '100',
    cell: 'status',
  },
  {
    colKey: 'op',
    title: '操作',
    width: '180',
    cell: 'op',
  },
];

// 规格表格列定义
const specColumns = [
  {
    colKey: 'key',
    title: '参数名称',
    width: '200',
  },
  {
    colKey: 'value',
    title: '参数值',
  },
];

// 模拟数据
const products = ref([
  {
    id: '1001',
    name: '高清摄像机',
    model: 'HDC-X100',
    category: '监控设备',
    manufacturer: '海康威视',
    productionDate: '2023-03-15',
    status: '在用',
    description: '高清网络摄像机，支持红外夜视功能，IP67防水等级',
    image: 'https://placeholder.pics/svg/300x200/DEDEDE/555555/Camera',
    specifications: [
      { key: '分辨率', value: '1920x1080' },
      { key: '帧率', value: '30fps' },
      { key: '防护等级', value: 'IP67' },
      { key: '工作温度', value: '-30°C ~ 60°C' },
      { key: '功耗', value: '5W' },
    ],
  },
  {
    id: '1002',
    name: '温湿度传感器',
    model: 'THS-2000',
    category: '传感器',
    manufacturer: '西门子',
    productionDate: '2023-04-20',
    status: '在用',
    description: '高精度温湿度传感器，适用于管廊环境监测',
    image: 'https://placeholder.pics/svg/300x200/DEDEDE/555555/Sensor',
    specifications: [
      { key: '温度范围', value: '-40°C ~ 80°C' },
      { key: '温度精度', value: '±0.3°C' },
      { key: '湿度范围', value: '0% ~ 100% RH' },
      { key: '湿度精度', value: '±2% RH' },
      { key: '供电电压', value: 'DC 12V' },
    ],
  },
  {
    id: '1003',
    name: '气体检测仪',
    model: 'GD-500',
    category: '传感器',
    manufacturer: '霍尼韦尔',
    productionDate: '2023-02-10',
    status: '维修',
    description: '多气体检测仪，可检测CH4、CO、H2S等有害气体',
    image: 'https://placeholder.pics/svg/300x200/DEDEDE/555555/Gas%20Detector',
    specifications: [
      { key: '检测气体', value: 'CH4, CO, H2S, O2' },
      { key: '检测范围(CH4)', value: '0 ~ 100% LEL' },
      { key: '检测范围(CO)', value: '0 ~ 1000 ppm' },
      { key: '检测范围(H2S)', value: '0 ~ 100 ppm' },
      { key: '检测范围(O2)', value: '0 ~ 30% vol' },
      { key: '响应时间', value: '< 30s' },
    ],
  },
  {
    id: '1004',
    name: '智能控制器',
    model: 'SC-2000',
    category: '控制设备',
    manufacturer: '施耐德',
    productionDate: '2023-05-05',
    status: '在用',
    description: '管廊环境智能控制器，支持远程控制和自动化管理',
    image: 'https://placeholder.pics/svg/300x200/DEDEDE/555555/Controller',
    specifications: [
      { key: 'CPU', value: 'ARM Cortex-A53' },
      { key: '内存', value: '2GB DDR4' },
      { key: '存储', value: '32GB eMMC' },
      { key: '接口', value: 'RS485, Ethernet, USB' },
      { key: '工作温度', value: '-20°C ~ 70°C' },
      { key: '防护等级', value: 'IP65' },
    ],
  },
]);

const loading = ref(false);
const searchText = ref('');
const modalVisible = ref(false);
const modalTitle = ref('添加产品');
const confirmLoading = ref(false);
const formRef = ref(null);
const currentId = ref(null);
const detailsVisible = ref(false);
const currentProduct = ref(null);
const deleteConfirmVisible = ref(false);
const productToDelete = ref(null);

// 表单状态
const formState = reactive({
  name: '',
  model: '',
  category: '监控设备',
  manufacturer: '',
  productionDate: null,
  status: '在用',
  description: '',
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  model: [{ required: true, message: '请输入产品型号', trigger: 'blur' }],
  category: [{ required: true, message: '请选择产品类别', trigger: 'change' }],
  manufacturer: [{ required: true, message: '请输入制造商', trigger: 'blur' }],
  productionDate: [{ required: true, message: '请选择生产日期', trigger: 'change' }],
  status: [{ required: true, message: '请选择使用状态', trigger: 'change' }],
};

// 根据搜索条件过滤产品
const filteredProducts = computed(() => {
  if (!searchText.value) {
    return products.value;
  }
  const keyword = searchText.value.toLowerCase();
  return products.value.filter(
    (product) =>
      product.name.toLowerCase().includes(keyword) ||
      product.model.toLowerCase().includes(keyword) ||
      product.category.toLowerCase().includes(keyword) ||
      product.manufacturer.toLowerCase().includes(keyword)
  );
});

// 搜索处理
const onSearch = () => {
  // 搜索逻辑已通过计算属性实现
};

// 添加产品
const handleAdd = () => {
  resetForm();
  modalTitle.value = '添加产品';
  modalVisible.value = true;
  currentId.value = null;
};

// 编辑产品
const handleEdit = (row) => {
  modalTitle.value = '编辑产品';
  modalVisible.value = true;
  currentId.value = row.id;
  
  // 填充表单数据
  formState.name = row.name;
  formState.model = row.model;
  formState.category = row.category;
  formState.manufacturer = row.manufacturer;
  formState.productionDate = dayjs(row.productionDate).toDate();
  formState.status = row.status;
  formState.description = row.description;
};

// 查看产品详情
const handleView = (row) => {
  currentProduct.value = { ...row };
  detailsVisible.value = true;
};

// 显示删除确认对话框
const showDeleteConfirm = (row) => {
  productToDelete.value = row;
  deleteConfirmVisible.value = true;
};

// 确认删除产品
const confirmDelete = () => {
  if (productToDelete.value) {
    products.value = products.value.filter(item => item.id !== productToDelete.value.id);
    MessagePlugin.success('产品已删除');
    productToDelete.value = null;
  }
};

// 模态框确认
const handleModalOk = () => {
  formRef.value.validate().then((result) => {
    if (result === true) {
      confirmLoading.value = true;
      
      setTimeout(() => {
        if (currentId.value) {
          // 更新产品
          const index = products.value.findIndex(item => item.id === currentId.value);
          if (index !== -1) {
            products.value[index] = {
              ...products.value[index],
              name: formState.name,
              model: formState.model,
              category: formState.category,
              manufacturer: formState.manufacturer,
              productionDate: dayjs(formState.productionDate).format('YYYY-MM-DD'),
              status: formState.status,
              description: formState.description,
            };
            MessagePlugin.success('产品已更新');
          }
        } else {
          // 添加产品
          const newId = (Math.max(...products.value.map(d => parseInt(d.id))) + 1).toString();
          products.value.push({
            id: newId.padStart(4, '0'),
            name: formState.name,
            model: formState.model,
            category: formState.category,
            manufacturer: formState.manufacturer,
            productionDate: dayjs(formState.productionDate).format('YYYY-MM-DD'),
            status: formState.status,
            description: formState.description,
            image: 'https://placeholder.pics/svg/300x200/DEDEDE/555555/New%20Product',
            specifications: [],
          });
          MessagePlugin.success('产品已添加');
        }
        
        modalVisible.value = false;
        confirmLoading.value = false;
      }, 500);
    }
  }).catch(error => {
    console.log('验证失败:', error);
  });
};

// 重置表单
const resetForm = () => {
  formState.name = '';
  formState.model = '';
  formState.category = '监控设备';
  formState.manufacturer = '';
  formState.productionDate = null;
  formState.status = '在用';
  formState.description = '';
  
  // 重置表单验证状态
  if (formRef.value) {
    formRef.value.reset();
  }
};

// 生命周期钩子
onMounted(() => {
  // 这里可以添加从API获取产品列表的逻辑
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
  }, 500);
});
</script>

<style scoped>
.product-info {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
}

.product-details {
  margin-bottom: 20px;
}

.product-image {
  margin-top: 24px;
}

.image-container {
  display: flex;
  justify-content: center;
  margin-top: 12px;
}

.image-container img {
  max-width: 100%;
  max-height: 300px;
  object-fit: contain;
}

.product-specs {
  margin-top: 24px;
}
</style> 